<template>
  <el-container class="admin-panel">
    <el-header>
      <h1>系统消息管理</h1>
    </el-header>
    <el-main>
      <div class="new-message">
        <h2>发送新消息</h2>
        <el-input type="textarea" v-model="newMessage" placeholder="输入系统消息" rows="6" maxlength="200"
          resize=none></el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
      <div class="history-messages">
        <h2>历史消息</h2>

        <el-table :data="messages">
          <el-table-column prop="xx" label="消息内容"/>
          <el-table-column prop="date" label="发送时间"/>
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button type="danger" @click.stop="confirmDelete('system', scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useRoute } from 'vue-router'
import { admin_IPC_send, admin_IPC_recv, admin_DELETE_msg} from '@/apis/admin_IPC.js';
import { getCurrentDateString } from '@/utils/currentTime.js';


const { proxy } = getCurrentInstance();
const route = useRoute()
const username = route.params.username
const newMessage = ref('');
const date = ref('');
const messages = ref([]);

// 获取所有历史消息
const fetchMessages = async () => {
  try {
    const response = await admin_IPC_recv(proxy);
    messages.value = response.data.system.map(message => ({
      xx: message.xx,
      id: message.id,
      date: message.date,
    }));
  } catch (error) {
    console.error('获取消息失败', error);
  }
};

// 发送新消息
const sendMessage = async () => {
  if (newMessage.value.trim() === '') {
    alert('消息内容不能为空');
    return;
  }
  try {
    date.value = getCurrentDateString();
    await admin_IPC_send(newMessage.value, date.value, proxy);
    
    const response = await admin_IPC_recv(proxy);
    const systemMessages = response.data.system;
    const newMessageObj = systemMessages[systemMessages.length - 1]; // 获取最后一个消息对象

    messages.value.push({
      xx: newMessageObj.xx,
      id: newMessageObj.id,
      date: newMessageObj.date,
    });

    newMessage.value = '';
  } catch (error) {
    console.error('发送消息失败', error);
  }
};

//删除某条信息
const deleteMessage = async (type, id) => {
  console.log(id);
  try {
    const response = await admin_DELETE_msg(type, id, proxy);
    const index = messages.value.findIndex(message => message.id === id);
    if (index !== -1) {
      messages.value.splice(index, 1);
    }
  } catch (error) {
    console.error('Failed to delete message:', error);
  }
};

//确认删除
const confirmDelete = (type, row) => {
  ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const message = findMessageById(row);
    deleteMessage(type, message.id);
  }).catch(() => {});
};

const findMessageById = (row) => {
  return messages.value.find(message => message.xx === row.xx && message.date === row.date);
};

// 组件挂载时获取历史消息
onMounted(() => {
  fetchMessages();
});
</script>

<style scoped>
.admin-panel {
  background-color: white;
  border-radius: 10px;
  margin-top: 2%;
  padding-top: 10px;
  width: 100%;
  height: 70%;
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
}

.new-message,
.history-messages {
  margin-bottom: 20px;
}

.new-message {
  width: 60%;
}

.new-message .el-input {
  margin-bottom: 10px;

}

.new-message .el-button {
  margin-top: 10px;
}
</style>